import WebHeader from '@/www/components/WebHeader'
import WebFooter from '@/www/components/WebFooter'
import { getQuote, uploadFile, postQuoteOrder } from '@/apiv2/quote'

const CODE = 'DisplayShelf'

export default {
  components: { WebHeader, WebFooter },
  data() {
    return {
      quoteData: undefined,
      checkValue: {

      },

      quoteValue: {
        category: undefined,
        customQuantity: 1,
        style: 1,
        quantity: undefined,
        size: undefined,
        customLength: undefined,
        customWidth: undefined10d
      },
      customSize:true,
      user: undefined,
      quote: undefined,
      quoteList: undefined,
      detail: undefined,
      fileList: [],
      postData: {
        quantity: undefined,
        detail: undefined,
        amount: undefined,
        fileIds: undefined
      },
      note: undefined
    }
  },

  created(){
    const user = JSON.parse(localStorage.getItem('user'))
    this.user = user

    getQuote(CODE).then(res => {
      let quoteData = res.config
      this.quoteValue.category = quoteData.cateData.list[0].name
      this.quoteData = quoteData
    })
  },

  methods: {

    getQuote(){
      let detail = ''
      let {customSize,quoteData,quoteValue,checkValue,postData} = this

      if(customSize && (!quoteValue.customLength || !quoteValue.customWidth)){
        this.$message.error('请输入自定义尺寸')
        return
      }


      let length = parseInt(quoteValue.customLength)
      let width = parseInt(quoteValue.customWidth)

      let finalQantity = parseInt(quoteValue.customQuantity)

      detail += quoteValue.category +'，'
        + '尺寸' + length + '*' + width +'，'
        + finalQantity + quoteData.param.unit

      let price = undefined
      for(let i = 0; i < quoteData.cateData.list.length; i++){
        let item = quoteData.cateData.list[i]
        if(quoteValue.category == item.name){
          price = item.price
          break
        }
      }

      let area = (parseFloat(length) * parseFloat(width) / parseFloat(10000)) * parseFloat(finalQantity)

      let discount = 1.0
      for(let i = 0; i < quoteData.process.cateDiscountList.length; i++){
        let item = quoteData.process.cateDiscountList[i]
        if(area >= parseFloat(item.start) && area <= parseFloat(item.end)){
          discount = parseFloat(item.discount)
          break
        }
      }

      let materialAmount = parseFloat(price) * area * discount

      let quoteList = [{
        materialAmount: materialAmount.toFixed(2),
        quantity: finalQantity,
        processAmount: 0,
        totalAmount: materialAmount.toFixed(2)
      }]

      let defaultFlag = false
      postData.amount = materialAmount.toFixed(2)
      postData.detail = detail
      this.postData = postData
      this.quoteList = quoteList
    },

    //匹配最终出纸尺寸和单张拼数
    matchSizePerCount(length,width){
      let sizeList = this.quoteData.sizeData.list

      //小于最小尺寸，按最小尺寸拼1个
      let minLong = parseInt(this.quoteData.param.minSize.split('*')[0])
      let minShort = parseInt(this.quoteData.param.minSize.split('*')[1])
      if(length <= minLong && width <= minShort){
        return {
          size: this.quoteData.sizeData.list[0],
          countPerPage: 1
        }
      }

      for(let i = 0; i < sizeList.length; i++){
        let sizeStr = sizeList[i].match(/\d+\*\d+/)[0]
        let l = parseInt(sizeStr.split('*')[0])
        let w = parseInt(sizeStr.split('*')[1])
        let {long,short} = this.findLongAndShort(l,w)
        if(length <= long && width <= short){
          return {
            size: sizeList[i],
            countPerPage: parseInt(long/length) * parseInt(short/width)
          }
        }
      }
      return undefined
    },

    //匹配数量阶梯
    matchStep(quantity){
      let returnQuantity = undefined
      let list = this.quoteData.stepData.list
      for(let i = 0; i < list.length; i++){
        if(quantity <= parseInt(list[i])){
          returnQuantity = parseInt(list[i])
          break
        }
      }
      return returnQuantity
    },

    //确认长边短边
    findLongAndShort(l,w){
      return {
        long: l >= w ? l : w,
        short: w <= l ? w : l
      }
    },

    //判断输入尺寸是否系小于或者等于指定尺寸
    checkIsLessOrEqualThanTargetSize(length,width,targetLength,targetWidth){
      let flag = false
      let long = undefined
      let short = undefined
      if(length >= width){
        long = length
        short = width
      }else{
        long = width
        short = length
      }

      if((long <= 420 && short <= 285) || (long <= 570 && short <= 210)){
        flag = true
      }

      return flag
    },


    //自定义尺寸切换
    onCustomSizeToggle(){
      this.quoteValue.customLength = undefined
      this.quoteValue.customWidth = undefined
    },

    selectQuantity(){
      if(this.quoteValue.quantity){
        this.quoteValue.customQuantity = undefined
      }
    },
    customQuantity(){
      if(this.quoteValue.customQuantity){
        this.quoteValue.quantity = undefined
      }else{
        this.quoteValue.quantity = this.quoteData.stepData.list[0]
      }
    },

    syncCheck(name,target){
      if(this.checkValue[name]){
        this.checkValue[target] = true
      }
    },

    offCheck(name,target){
      if(!this.checkValue[name]){
        this.checkValue[target] = false
      }
    },

    submitOrder(){
      const {fileList,postData} = this

      if(fileList.length < 1){
        this.$message.error('请上传设计稿')
        return
      }

      let fileIds = [];
      fileList.forEach(item => {
        fileIds.push(item.id)
      })
      postData.fileIds = fileIds

      const loading = this.$loading({
        lock: true,
        text: '正在创建订单',
        spinner: 'el-icon-loading',
        background: 'rgba(0,0,0,0.7)'
      });

      postQuoteOrder(postData).then(res => {
        loading.close()
        this.$message.success('成功创建订单')
        this.$router.push({
          path: '/submitOrder',
          query: { id : res.id}
        })
      }).catch(err => {
        loading.close()
        this.$message.error('创建订单失败')
      })
    },

    handleUpload: async function(data){
      const formData = new FormData()
      formData.append('file', data.file)
      const res = await uploadFile(formData)
      let fileList = this.fileList
      fileList.push(res.file)
      this.fileList = fileList
      console.log(fileList)
    },
  }
}
